package com.bzchao.ds.demo.common.config.ds;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.bzchao.ds.core.config.DynamicDataSource;
import com.bzchao.ds.core.dao.DataSourceDao;
import com.bzchao.ds.demo.tenant.entity.TenantInfo;
import com.bzchao.ds.demo.tenant.mapper.TenantInfoMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Component
public class DataSourceDaoImpl extends DataSourceDao {

    @Autowired
    private TenantInfoMapper tenantInfoMapper;

    @Override
    public List<Map<String, String>> listEnableDataSource() {
        LambdaQueryWrapper<TenantInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TenantInfo::getEnable, true);
        DynamicDataSource.switchConnect("master");
        List<TenantInfo> tenantInfoList = tenantInfoMapper.selectList(queryWrapper);
        DynamicDataSource.clearDataSource();
        List<Map<String, String>> mapList = tenantInfoList.stream()
                .map(tenantInfo -> {
                    Map<String, String> map = new HashMap<>();
                    map.put("connectId", tenantInfo.getTenantId());
                    map.put("datasource.url", tenantInfo.getDataSourceUrl());
                    map.put("datasource.username", tenantInfo.getDataSourceUsername());
                    map.put("datasource.password", tenantInfo.getDataSourcePassword());
                    map.put("datasource.driverClass", tenantInfo.getDataSourceDriver());
                    return map;
                }).collect(Collectors.toList());
        return mapList;
    }
}
